package cn.com.dycc.common.attach.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.common.attach.service.AttachService;
import cn.com.dycc.common.controller.BaseController;
import cn.com.dycc.util.JsonObjectResult;
import cn.com.dycc.util.PathUtil;
import cn.com.dycc.util.PropertiesUtil;
import sun.misc.BASE64Decoder;

@Controller  
@RequestMapping("/attach") 
public class AttachController extends BaseController{
	
	@Resource(name="attachService")
	private AttachService attachService;
	
    /**  
     * 一次上传单个文件到服务器和数据库  
     * @param request  
     * @return  
     * @throws IOException  
     */  
    @RequestMapping("/upFiles.do")  
    @ResponseBody  
    public JsonObjectResult upFiles(HttpServletRequest request) throws IOException{  
        //String fileName=request.getParameter("fileName");  
        // 转型为MultipartHttpRequest：     
    	
 //   	MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
 //   	MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;     
        // 获得文件：  
        MultipartFile file = multipartRequest.getFile("file"); 
 //       System.out.println("file="+file);
        //获取文件参数   
       // 获取我们准备好的用于存储上传文件的绝对路径.  
  //      String paths = request.getSession().getServletContext().getRealPath("file"); 
 //       System.out.println(paths); 
        
        String all_title=new String(file.getOriginalFilename().getBytes(),"utf-8");//文件原始名字
        String title = all_title.substring(0,all_title.lastIndexOf("."));
  //      System.out.println("title="+title);
//      title = new String(title.getBytes("iso8859-1"),"utf-8");
      //  System.out.println("title=:"+title); 
      //文件类型
      // String at=file.getContentType();
      // System.out.println("at="+at);
     	//服务器路径
        ///home/tomcat/tomcat/temp/
        String attach_path= PathUtil.temp_path;
    //   +title.substring(title.indexOf("."));//服务器路径  
        //最大2147483647字节 
        Long long_attach_size = file.getSize();
        String attach_size = long_attach_size.toString();
   //     System.out.println(attach_size);
        //内容
        //byte[] byte_attach_content =file.getBytes();
       // String attach_content = new String(byte_attach_content);
        //System.out.println(attach_content);
        //附件后缀
        String attach_ext = all_title.substring(all_title.lastIndexOf("."));
        System.out.println("attach_ext="+attach_ext);
        //加载通过的附件路径
        String pas_ext = PropertiesUtil.readProperties("db/config.properties","pass_attach_ext");
        String[] arr_pas_ext = pas_ext.split("/");
//        System.out.println("arr_pas_ext="+arr_pas_ext);
        //通过后放行附件上传，不通过终止上传
        boolean ext_flag = true;
		for(String pas : arr_pas_ext){
//			System.out.println("pas="+pas);
			if(attach_ext.equals(pas)){
				ext_flag = false;
				break;
			}
		}
		if(ext_flag){
			return new JsonObjectResult(1,"","该类型附件不允许上传！","");
		}
        
        
     //   System.out.println(attach_ext);
        //组织标识
		//String org_id = (request.getSession().getAttribute("top_dept_no")).toString();
        //创建人
		//String user_id = (request.getSession().getAttribute("id")).toString();
        //存到服务器上  
        //String realPath = request.getSession().getServletContext().getRealPath("/files");//servlet下的路径  
        //String files_server_path=realPath+System.currentTimeMillis()+files_origin_name.substring(files_origin_name.indexOf("."));  
    //    System.out.println(attach_path);
        String new_attach_path = attach_path+attachService.findAttach_path_seq()+attach_ext;
        if(file!=null){  
            File filepath=new File(attach_path);  
            if(!filepath.exists()){//判断改路径是否存在  
                filepath.mkdirs();  
            }  
            file.transferTo(new File(new_attach_path)); 
        }
        
        
        //将上传到服务器附件的部分信息返回
        Attach attach = new Attach();
        attach.setAttach_ext(attach_ext);
        attach.setAttach_path(new_attach_path);
        attach.setAttach_size(attach_size);
//      attach.setAttach_type(attach_type);
//      attach.setMessage_no(message_no);
//      attach.setOpt_user_id(user_id);
        attach.setTitle(title);
//      attach.setOrg_id(org_id);
//        System.out.println(title);
//        
//      JsonResult jr = attachService.insertAttach(attach);
        return new JsonObjectResult(attach);
    }
    
    
    /** 
     * 一次性上传多个文件 
     * @param request 
     * @param files 
     * @return 
     * @throws Exception 
     */  
    @RequestMapping("/addFiles.do")  
    @ResponseBody  
    public JsonObjectResult addFiles(HttpServletRequest request,@RequestParam MultipartFile[] files) throws Exception {  
        // 判断file数组不能为空并且长度大于0  
    	List<Attach> list = new ArrayList<Attach>();
        if (files != null && files.length > 0) {  
        	//服务器路径 
        	//"/home/tomcat/tomcat/temp/"
            String attach_path= PathUtil.temp_path;
            String pas_ext = PropertiesUtil.readProperties("db/config.properties","pass_attach_ext");
            // 循环获取file数组中得文件  
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i]; 
                //获取附件对象信息
                Attach attach = new Attach();
                // 保存文件  
                // 判断文件是否为空  
              //  System.out.println(file);
                if (!file.isEmpty()) {  
                    // 文件名 
                	
                    String all_title=new String(file.getOriginalFilename().getBytes(),"utf-8");//文件原始名字
                    String title = all_title.substring(0,all_title.lastIndexOf("."));
//                	String title = all_title.substring(0,all_title.indexOf("."));
//                	title = new String(title.getBytes("iso8859-1"),"utf-8");
                	//文件长度
                	Long long_attach_size = file.getSize();
                    String attach_size = long_attach_size.toString();
                    //附件后缀
                    String attach_ext = all_title.substring(all_title.lastIndexOf("."));
 //                   System.out.println(attach_ext);
                    String[] arr_pas_ext = pas_ext.split("/");
                    //通过后放行附件上传，不通过终止上传
                    boolean ext_flag = true;
            		for(String pas : arr_pas_ext){
//            			System.out.println("ot="+ot);
            			if(attach_ext.equals(pas)){
            				ext_flag = false;
            				break;
            			}
            		}
            		if(ext_flag){
            			return new JsonObjectResult(1,"","该类型附件不允许上传！","");
            		}
                    
                    String new_attach_path = 
                    		attach_path+attachService.findAttach_path_seq()+attach_ext;
                    // 文件保存路径 
                   // String path = "D:/addfiles/" + title;
                    File filepath=new File(attach_path); 
                   // System.out.println(file.getOriginalFilename());
                    if(!filepath.exists()){//判断改路径是否存在 
                        filepath.mkdirs(); 
                    }
                    attach.setAttach_ext(attach_ext);
                    attach.setAttach_path(new_attach_path);
                    attach.setAttach_size(attach_size);
                    attach.setTitle(title);
                    list.add(attach);
                    // 转存文件  
                    file.transferTo (new File
                    		(new_attach_path)); 
                }  
              
            }  
        }  
        return new JsonObjectResult(list); 
    }
    
    
    /** 
     * 下载文件  
     * @param request 
     * @param response 
     * @return 
     * @throws IOException 
     */  
    @RequestMapping("/downFiles.do")  
    public void downFiles(HttpServletRequest request,HttpServletResponse response,String id) throws IOException{  
    	Attach attach=attachService.getAttach(id,request);  
        request.setCharacterEncoding("UTF-8");  
        response.setContentType("multipart/form-data;charset=UTF-8");  
        //response.addHeader("Content-Disposition","attachment; filename="+files.getFiles_origin_name());  
        //+new String(attach.getTitle().getBytes("utf-8"),"iso-8859-1")
        //设置文件名字  
        response.setHeader("Content-Disposition","attachment; filename="+new String
        		(attach.getTitle().getBytes("utf-8"),"iso-8859-1")+attach.getAttach_ext());
       // System.out.println();  
        //路径 attach.getAttach_path()
        FileInputStream fis=new FileInputStream(attach.getAttach_path());//读取文件  
        OutputStream os=response.getOutputStream();//创建输出流  
        byte[] bt=new byte[1024];  
        while(fis.read(bt)!=-1){  
            os.write(bt);  
        }
    //    System.out.println("1");
        fis.close();  
        os.flush();  
        os.close();  
        
     //   return "下载成功！";  
    } 
    
    
    /** 
     * 一次性上传多个文件 (测试)
     * @param request 
     * @param files 
     * @return 
     * @throws Exception 
     */  
    @RequestMapping("/webaddFiles.do")  
    @ResponseBody  
    public JsonObjectResult webAddFiles(HttpServletRequest request,@RequestParam MultipartFile[] file) throws Exception {  
        // 判断file数组不能为空并且长度大于0  
    	List<Attach> list = new ArrayList<Attach>();
        if (file != null && file.length > 0) {  
        	//服务器路径 
        	//"/home/tomcat/tomcat/temp/"
            String attach_path= PathUtil.temp_path;
            // 循环获取file数组中得文件  
            for (int i = 0; i < file.length; i++) {
                MultipartFile f = file[i]; 
                //获取附件对象信息
                Attach attach = new Attach();
                // 保存文件  
                // 判断文件是否为空  
              //  System.out.println(file);
                if (!f.isEmpty()) {  
                    // 文件名 
                	String all_title = f.getOriginalFilename();
                	String title = all_title.substring(0,all_title.lastIndexOf("."));
                	title = new String(title.getBytes("iso8859-1"),"utf-8");
                	//文件长度
                	Long long_attach_size = f.getSize();
                    String attach_size = long_attach_size.toString();
                    //附件后缀
                    String attach_ext = all_title.substring(all_title.lastIndexOf("."));
//                    System.out.println(attach_ext);
                    
                    String new_attach_path = 
                    		attach_path+attachService.findAttach_path_seq()+attach_ext;
                    // 文件保存路径 
                   // String path = "D:/addfiles/" + title;
                    File filepath=new File(attach_path); 
                   // System.out.println(file.getOriginalFilename());
                    if(!filepath.exists()){//判断改路径是否存在 
                        filepath.mkdirs(); 
                    }
                    attach.setAttach_ext(attach_ext);
                    attach.setAttach_path(new_attach_path);
                    attach.setAttach_size(attach_size);
                    attach.setTitle(title);
                    list.add(attach);
                    // 转存文件  
                    f.transferTo (new File
                    		(new_attach_path)); 
                }  
              
            }  
        }  
        return new JsonObjectResult(list); 
    }
    
    @RequestMapping(value="/upbase.do",method=RequestMethod.POST)
    @ResponseBody
    public JsonObjectResult basePic(@RequestParam String base64Data){  
       
    	Attach attach = new Attach();
    	String size = null;
    	String str = null;
        try{  
        	
 //       	System.out.println("base64Data1="+base64Data);
        	
            String dataPrix = "";
 //           String data = "";

            if(base64Data == null || "".equals(base64Data)){
                throw new Exception("请选择上传图片！");
            }else{
            	
 //           	base64Data = java.net.URLDecoder.decode(base64Data,"UTF-8"); 
            	
 //           	System.out.println("base64Data2="+base64Data);
            	
            	 dataPrix = base64Data.substring(0,base64Data.indexOf("base64,"));
            	
//            	 System.out.println("dataPrix="+dataPrix);
            	
            	 str=base64Data.substring(base64Data.indexOf("base64,")+7);// 1.需要计算文件流大小，首先把头部的,（注意有逗号）去掉。
//                 System.out.println("str="+str);
            	 
            	 Integer equalIndex= str.indexOf("=");//2.找到等号，把等号也去掉
                 if(str.indexOf("=")>0) {
                     str=str.substring(0, equalIndex);
                 }
                 Integer strLength=str.length();//3.原来的字符流大小，单位为字节
                 size=String.valueOf((strLength-(strLength/8)*2));//4.计算后得到的文件流大小，单位为字节
         
            }
            String suffix = "";
            //忽略大小写
            if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//编码的jpeg图片数据
                suffix = ".jpg";
            } else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//编码的icon图片数据
                suffix = ".ico";
            } else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//编码的gif图片数据
                suffix = ".gif";
            } else if("data:image/png;".equalsIgnoreCase(dataPrix)){//编码的png图片数据
                suffix = ".png";
            }else{
                throw new Exception("上传图片格式不合法");
            }
            ////Base64解码 
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = decoder.decodeBuffer(str);
            
            String attach_path= PathUtil.temp_path;
            
            String file_name = attachService.findAttach_path_seq();
            
            //路径
            String new_attach_path = attach_path+file_name+suffix;
            
            File filepath=new File(attach_path); 
           // System.out.println(file.getOriginalFilename());
            if(!filepath.exists()){//判断改路径是否存在 
                filepath.mkdirs(); 
            }
            
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {
                	//调整异常数据  
                    b[i]+=256;  
                }  
            }
            
            OutputStream out = new FileOutputStream(new_attach_path);      
            out.write(b);  
            out.flush();  
            out.close();
            
            attach.setAttach_ext(suffix);
            attach.setAttach_path(new_attach_path);
            attach.setAttach_size(size);
            attach.setTitle(file_name);
            
          
        }catch (Exception e) {
			e.printStackTrace();
		}
            
        return new JsonObjectResult(attach);
    }
    
    //根据messge_no和附件类型获取附件
    @RequestMapping("findlist.do")
    @ResponseBody
    public JsonObjectResult findAttachByMesNoAndType(HttpServletRequest request,String message_no,Integer attach_type){
    	List<Attach> list = attachService.findAttachByMesNoAndType(message_no, attach_type,request);
    	return new JsonObjectResult(list);
    }
    
    //删除附件
    @RequestMapping("delattach.do")
    @ResponseBody
    public JsonObjectResult delAttach(HttpServletRequest request,String id){
    	String mes = attachService.delAttach(request,id);
    	return new JsonObjectResult(mes);
    }
    
    
}
